package com.lebang.service;

import com.alibaba.fastjson.JSON;
import com.lebang.configuration.datasource.DataSource;
import com.lebang.domain.CencesEarnDay;
import com.lebang.domain.TaskWorthDetail;
import com.lebang.domain.TaskWorthRecord;
import com.lebang.entity.BlackAppStoreRecord;
import com.lebang.example.TaskWorthDetailExample;
import com.lebang.example.TaskWorthRecordExample;
import com.lebang.mapper.CencesEarnDayMapper;
import com.lebang.mapper.TaskWorthDetailMapper;
import com.lebang.mapper.TaskWorthRecordMapper;
import com.lebang.model.MyConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 任务价值录制
 *
 * @Author xwj
 * @Date 2020-09-18
 */
@Service
@Slf4j
public class TaskWorthRecordService extends BaseService<TaskWorthRecord, Integer, TaskWorthRecordExample> {

    @Autowired
    private TaskWorthRecordMapper taskWorthRecordMapper;

    @Autowired
    private CencesEarnDayMapper cencesEarnDayMapper;

    @Autowired
    private TaskWorthDetailMapper taskWorthDetailMapper;

    /**
     * 检查当前应用录入日期指定数据源是否存在
     * @param vo
     * @return
     */
    public boolean checkExit(TaskWorthRecord vo) {
       // Integer isExit = taskWorthRecordMapper.selectByTimeSdk(vo.getAppid(),vo.getTime(),vo.getSdkKey());
        Integer isExit = taskWorthRecordMapper.selectByTimeSdkAppStore(vo.getAppid(),vo.getTime(),vo.getSdkKey(),vo.getAppStore());
        if(isExit!=null){
            return true;
        }
        return false;
    }

    @DataSource("commonDB")
    public void update(TaskWorthRecord vo) {
        taskWorthRecordMapper.updateByPrimaryKeySelective(vo);
    }

    @DataSource("commonDB")
    public void insert(TaskWorthRecord vo) {
        taskWorthRecordMapper.insertSelective(vo);
    }

    public TaskWorthRecord checkData(TaskWorthRecord vo) {
    //CencesEarnDay cencesEarnDay = cencesEarnDayMapper.selectBySdkTime(vo.getSdkKey(),vo.getTime(), MyConfig.getEnv());
    CencesEarnDay cencesEarnDay = cencesEarnDayMapper.selectBySdkTimeAppStore(vo.getSdkKey(),vo.getTime(), MyConfig.getEnv(),vo.getAppStore());
    if(cencesEarnDay==null){
        //计算
        //4.1单任务价值：收益/任务数（保留两位小数点）
        vo.setTaskWorth(BigDecimal.valueOf(0));
        //4.2每点击价值：收益/点击数（保留两位小数点）
        vo.setClickWorth(BigDecimal.valueOf(0));
        //4.3人均任务数：任务数/对应完成人数（保留两位小数点）
        vo.setTaskNumEvery(BigDecimal.valueOf(0));

        //4.5任务人数：该数据源当天完成的人数
        vo.setFinishNum(0);
        //4.6任务数：该数据源当天完成的任务数
        vo.setTaskFinishNum(0);
    }else{
        //计算
        if(cencesEarnDay.getSuccessCount()==0){
            vo.setTaskWorth(BigDecimal.ZERO.setScale(2,BigDecimal.ROUND_DOWN));
        }else{
            //4.1单任务价值：收益/任务数（保留两位小数点）
            vo.setTaskWorth(vo.getAward().divide(BigDecimal.valueOf(cencesEarnDay.getSuccessCount()),2, BigDecimal.ROUND_DOWN));
        }

        //4.2每点击价值：收益/点击数（保留两位小数点）
        vo.setClickWorth(vo.getAward().divide(BigDecimal.valueOf(vo.getClick()),2,BigDecimal.ROUND_DOWN));

        if(cencesEarnDay.getFinishNum()==0){
            vo.setTaskNumEvery(BigDecimal.ZERO.setScale(2,BigDecimal.ROUND_DOWN));
        }else{
            //4.3人均任务数：任务数/对应完成人数（保留两位小数点）
            vo.setTaskNumEvery(BigDecimal.valueOf(cencesEarnDay.getSuccessCount()).divide(BigDecimal.valueOf(cencesEarnDay.getFinishNum()),2,BigDecimal.ROUND_DOWN));
        }


        //4.5任务人数：该数据源当天完成的人数
        vo.setFinishNum(cencesEarnDay.getFinishNum());
        //4.6任务数：该数据源当天完成的任务数
        vo.setTaskFinishNum(cencesEarnDay.getSuccessCount());
    }

        //4.4CPM：收益/展示*1000（保留两位小数点）
        vo.setCpm(vo.getAward().multiply(BigDecimal.valueOf(1000)).divide(BigDecimal.valueOf(vo.getShow()),2,BigDecimal.ROUND_DOWN));
    return vo;

    }

    /**
     * 计算数据
     * @param recordList
     * @return
     */
    public List<TaskWorthRecord> calculationRecord(List<TaskWorthRecord> recordList) {
        List<CencesEarnDay> list = cencesEarnDayMapper.selectGroupbyTime(recordList,MyConfig.getEnv());
        list.forEach(s->{s.setSdkAppStore(s.getSdkKey()+":"+s.getBrand());});
        Map<String,List<CencesEarnDay>> map = list.stream().collect(Collectors.groupingBy(CencesEarnDay::getSdkAppStore));
        recordList.forEach(s->{
            //计算
            //4.1单任务价值：收益/任务数（保留两位小数点）
            s.setTaskWorth(BigDecimal.valueOf(0));
            //4.2每点击价值：收益/点击数（保留两位小数点）
            s.setClickWorth(BigDecimal.valueOf(0));
            //4.3人均任务数：任务数/对应完成人数（保留两位小数点）
            s.setTaskNumEvery(BigDecimal.valueOf(0));

            //4.5任务人数：该数据源当天完成的人数
            s.setFinishNum(0);
            //4.6任务数：该数据源当天完成的任务数
            s.setTaskFinishNum(0);
                //计算
                CencesEarnDay cencesEarnDay = sumData(map,s);
                if(cencesEarnDay.getSuccessCount()==0){
                    s.setTaskWorth(BigDecimal.ZERO.setScale(2,BigDecimal.ROUND_DOWN));
                }else{
                    //4.1单任务价值：收益/任务数（保留两位小数点）
                    s.setTaskWorth(s.getAward().divide(BigDecimal.valueOf(cencesEarnDay.getSuccessCount()),2, BigDecimal.ROUND_DOWN));
                }

                //4.2每点击价值：收益/点击数（保留两位小数点）
                s.setClickWorth(s.getAward().divide(BigDecimal.valueOf(s.getClick()),2,BigDecimal.ROUND_DOWN));

                if(cencesEarnDay.getFinishNum()==0){
                    s.setTaskNumEvery(BigDecimal.ZERO.setScale(2,BigDecimal.ROUND_DOWN));
                }else{
                    //4.3人均任务数：任务数/对应完成人数（保留两位小数点）
                    s.setTaskNumEvery(BigDecimal.valueOf(cencesEarnDay.getSuccessCount()).divide(BigDecimal.valueOf(cencesEarnDay.getFinishNum()),2,BigDecimal.ROUND_DOWN));
                }


                //4.5任务人数：该数据源当天完成的人数
                s.setFinishNum(cencesEarnDay.getFinishNum());
                //4.6任务数：该数据源当天完成的任务数
                s.setTaskFinishNum(cencesEarnDay.getSuccessCount());


            //4.4CPM：收益/展示*1000（保留两位小数点）
            s.setCpm(s.getAward().multiply(BigDecimal.valueOf(1000)).divide(BigDecimal.valueOf(s.getShow()),2,BigDecimal.ROUND_DOWN));
        });

        return recordList;
    }

    /**
     * 计算
     * @param map
     * @param s
     * @return
     */
    private CencesEarnDay sumData(Map<String, List<CencesEarnDay>> map, TaskWorthRecord s) {
        //编辑时写入的渠道
        String[] appStores =  s.getAppStore().split(",");
        CencesEarnDay cencesEarnDay = new CencesEarnDay(0,s.getAppStore(),s.getTime(),2,s.getSdkKey(),0,s.getAppid());

        for(String appStore:appStores){
            List<CencesEarnDay> list = map.get(s.getSdkKey()+":"+appStore);
            if(list==null){
                continue;
            }
            for(CencesEarnDay item:list){
                cencesEarnDay.setSuccessCount(item.getSuccessCount()+cencesEarnDay.getSuccessCount());
                cencesEarnDay.setFinishNum(item.getFinishNum()+cencesEarnDay.getFinishNum());
            }
        }
        return cencesEarnDay;
    }

    /**
     * 批量写入数据
     * @param recordList
     */
    @DataSource("commonDB")
    public void insertList(List<TaskWorthRecord> recordList) {
        LocalDate now = LocalDate.now();
        recordList.forEach(s->{
            s.setCreateTime(now);
            s.setAppid(MyConfig.getEnv());
            taskWorthRecordMapper.insertSelective(s);
            String[] appStores =  s.getAppStore().split(",");
            for(String appStore:appStores){
                TaskWorthDetail taskWorthDetail = new TaskWorthDetail();
                taskWorthDetail.setCreateTime(now);
                taskWorthDetail.setAppStore(appStore);
                taskWorthDetail.setRecordId(s.getId());
                taskWorthDetailMapper.insertSelective(taskWorthDetail);
            }



        });

    }

    public List<TaskWorthRecord> selectList(long row, Integer limit, List<String> appStores, Integer appId, String sdkKey, Integer star, Integer end,List<String> sList) {
        return taskWorthRecordMapper.selectList(row,limit,appStores,appId,sdkKey,star,end,sList);
    }

    public long countList(List<String> appStores, Integer appId, String sdkKey, Integer star, Integer end,List<String> sList) {
        return taskWorthRecordMapper.countList(appStores,appId,sdkKey,star,end,sList);
    }

    public List<Integer> selectTime(long row, Integer limit, Integer appId, String sdkKey, Integer star, Integer end,List<String> sList) {
        return taskWorthRecordMapper.selectTime(row,limit,appId,sdkKey,star,end,sList);
    }

    public long countAll(Integer appId, String sdkKey, Integer star, Integer end,List<String> sList) {
        return taskWorthRecordMapper.countAll(appId,sdkKey,star,end,sList);
    }

    public List<TaskWorthRecord> sumDataGroubySdk(long row, Integer limit,Integer appId, String sdkKey, Integer star, Integer end,List<String> sList) {
        return taskWorthRecordMapper.sumDataGroubySdk(row,limit,appId,sdkKey,star,end,sList);
    }

    /**
     * 计算数据源下所有渠道
     * @param records
     * @return
     */
    public List<TaskWorthRecord> sumAllAppStoreData(List<TaskWorthRecord> records) {

        records.forEach(s->{
            //4.1单任务价值：收益/任务数（保留两位小数点）
            if(s.getTaskFinishNum()==0){
                s.setTaskWorth(BigDecimal.ZERO);
            }else{
                s.setTaskWorth(s.getAward().divide(BigDecimal.valueOf(s.getTaskFinishNum()),2, BigDecimal.ROUND_DOWN));
            }
            if(s.getClick()==0){
                //4.2每点击价值：收益/点击数（保留两位小数点）
                s.setClickWorth(BigDecimal.ZERO);
            }else{
                //4.2每点击价值：收益/点击数（保留两位小数点）
                s.setClickWorth(s.getAward().divide(BigDecimal.valueOf(s.getClick()),2,BigDecimal.ROUND_DOWN));
            }

            if(s.getFinishNum()==0){
                //4.3人均任务数：任务数/对应完成人数（保留两位小数点）
                s.setTaskNumEvery(BigDecimal.ZERO);
            }else{
                //4.3人均任务数：任务数/对应完成人数（保留两位小数点）
                s.setTaskNumEvery(BigDecimal.valueOf(s.getTaskFinishNum()).divide(BigDecimal.valueOf(s.getFinishNum()),2,BigDecimal.ROUND_DOWN));
            }
           if(s.getShow()==0){
               //4.4CPM：收益/展示*1000（保留两位小数点）
               s.setCpm(BigDecimal.ZERO);
           }else{
               //4.4CPM：收益/展示*1000（保留两位小数点）
               s.setCpm(s.getAward().multiply(BigDecimal.valueOf(1000)).divide(BigDecimal.valueOf(s.getShow()),2,BigDecimal.ROUND_DOWN));
           }

            s.setAppStore("all");
        });
        return records;
    }

    /**
     * 删除录制详情记录表
     * @param id
     */
    @DataSource("commonDB")
    public void deleteByRecordId(Integer id) {
            TaskWorthDetailExample example = new TaskWorthDetailExample();
            example.createCriteria().andRecordIdEqualTo(id);
            taskWorthDetailMapper.deleteByExample(example);

    }

    @DataSource("commonDB")
    public void delete(Integer id) {

        taskWorthRecordMapper.deleteByPrimaryKey(id);
    }
}
